package org.linuxsogood.boot.grpc.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.linuxsogood.boot.grpc.MetricsServiceGrpc;
import org.linuxsogood.boot.grpc.StreamingExample;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.stream.Stream;

/**
 * @author liu.hongwei
 * @since 2020/11/17 17:57
 */
@Component
@Slf4j
public class MetricsClient {

    private MetricsServiceGrpc.MetricsServiceStub metricsServiceStub;

    @PostConstruct
    private void init() {
        final ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 6565).usePlaintext().build();
        metricsServiceStub = MetricsServiceGrpc.newStub(managedChannel);
    }

    public void stream() {
        final StreamObserver<StreamingExample.Metric> collect = metricsServiceStub.collect(new StreamObserver<StreamingExample.Average>() {
            @Override
            public void onNext(StreamingExample.Average value) {
                log.info("client Average: {}", value.getVal());
            }

            @Override
            public void onError(Throwable t) {

            }

            @Override
            public void onCompleted() {

            }
        });
        Stream.of(1L, 2L, 3L, 4L).map(l-> StreamingExample.Metric.newBuilder().setMetric(1).build()).forEach(collect::onNext);
        collect.onCompleted();
    }

}
